package com.mango.iot.gateway.http.srv;

import cn.hutool.core.util.IdUtil;
import com.mango.iot.gateway.http.consts.AppBizException;
import com.mango.iot.gateway.http.consts.ResultCode;
import com.mango.iot.gateway.http.controller.req.AuthReq;
import com.mango.iot.gateway.http.utils.AppBizExceptionUtil;
import com.mango.iot.gateway.http.utils.SignatureUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.SortedMap;
import java.util.TreeMap;

/**
 * 设备认证逻辑 Service
 *
 * @author liangfeihu
 * @since 2021/8/24 15:31
 */
@Slf4j
@Service
public class AuthService {

    @Autowired
    private TokenService tokenService;


    public String handleDeviceAuth(AuthReq authReq) throws AppBizException {
        validateTimestamp(authReq.getTimestamp());

        boolean authFlag = validateAuthSign(authReq);
        if (!authFlag) {
            throw AppBizExceptionUtil.build(ResultCode.PASSWORD_INCORRECT);
        }

        String token = IdUtil.fastSimpleUUID().replace("-", "");
        log.info("[auth] productKey={} deviceNo={} auth success", authReq.getProductKey(), authReq.getDeviceNo());

        tokenService.setTokenToCache(token, authReq);
        return token;
    }


    private void validateTimestamp(long timestamp) throws AppBizException {
        if (!SignatureUtil.verifyTimestamp(timestamp)) {
            throw AppBizExceptionUtil.build(ResultCode.INVALID_PARAMETER);
        }
    }

    private boolean validateAuthSign(AuthReq authReq) throws AppBizException {
        String deviceSecret = getDeviceSecret(authReq.getProductKey(), authReq.getDeviceNo());

        // 将sign、signmethod和version除外。
        SortedMap<String, String> map = new TreeMap<String, String>();
        map.put("productKey", authReq.getProductKey());
        map.put("deviceNo", authReq.getDeviceNo());
        map.put("clientId", authReq.getClientId());
        map.put("timestamp", authReq.getTimestamp().toString());

        return SignatureUtil.verifySignature(map, deviceSecret, authReq.getSignmethod(), authReq.getSign());
    }

    private String getDeviceSecret(String productKey, String deviceNo) throws AppBizException {

        return null;
    }

}
